<?php

namespace app\front\controller;
use app\common\model\MbtiOrder;
use app\common\model\MbtiTests;
use app\common\service\PayOrderService;
use app\lib\pay\AliPay;
use app\lib\pay\wxPay;
use think\Exception;
use think\facade\Log;
use think\response\Json;
use Yansongda\Pay\Pay as P;
class Pay extends Base
{
    /**
     * 支付宝跳转地址
     */
    public function alipayReturn()
    {
        $data = input('param.');
        if (empty($data['out_trade_no'])) {
            return redirect('/');
        }
            $order = MbtiOrder::where('order_no', $data['out_trade_no'])->find();
        if ($order['is_pay'] != 1) {
            return redirect('/');
        }
        $password = rand(10000000, 99999999);
        $sha256Hash = hash('sha256', $password);
        //更新密码
        MbtiTests::where('order_no', $order['business_order_no'])->update(['secret' => $sha256Hash,'secret_time' => time() + 600]);
        //跳转
        return redirect('/report?order_no=' . $order['business_order_no'] . "&secret=" . $sha256Hash);
    }

    /**
     * 支付宝回调地址
     * @throws \Yansongda\Pay\Exception\ContainerException
     * @throws \Yansongda\Pay\Exception\InvalidParamsException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function alipayCallback()
    {
        Log::info('alipayCallback 入参' . json_encode(request()->param()));

        P::config((new AliPay())->getConf());
        $result = P::alipay()->callback();
        Log::info('alipayCallback before' . gettype($result));
        $result = json_decode($result,true);
        Log::info('alipayCallback after' . gettype($result));
        Log::info('alipayCallback 解参' . json_encode($result));
        $order = MbtiOrder::where('order_no', $result['out_trade_no'])->find();
        if (empty($order) || $order['is_pay'] == 1) {
            return response()->code(200);
        }
        MbtiOrder::where('order_no', $result['out_trade_no'])
            ->update([
                'is_pay' => 1,
                'pay_time' => $result['gmt_payment'],
                'trade_no' => $result['trade_no']
            ]);
        return P::alipay()->success();

    }

    /**
     * 微信回调
     * @return string|\Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function wxCallback()
    {
        if (empty(request()->param())){
            return '';
        }
        Log::info('wx'.json_encode(request()->param()));

        return (new wxPay())->handleRefundedNotify();
    }

    /**
     * 查询微信支付订单
     * @return Json
     */
    public function checkPayStatus()
    {
        $wx = (new wxPay())->queryByOutTradeNumber(input('order_no'));
        if (!empty($wx['return_msg']) && !empty($wx['return_code']) && $wx['return_msg'] == "OK" && $wx['return_code'] == "SUCCESS" && $wx['trade_state_desc'] != "订单未支付") {
            MbtiOrder::where('order_no',$wx['out_trade_no'])
                ->where('pay_type','wx')
                ->update(['is_pay' => 1,'pay_time' => date('Y-m-d H:i:s'),'trade_no' => $wx['transaction_id']]);
        }
        return toJson(0, 'ok', $wx);
    }


    /**
     * 下单接口
     * @return string|Json
     * @throws Exception
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function pay()
    {
        $data = request()->param();
        if (empty($data['order_no'])) {
            return toJson(1, '支付订单不能为空');
        }
        if (!isset($data['pay_type'])) {
            return toJson(1, '支付方式不能为空');
        }
        if (!isset($data['order_type'])) {
            return toJson(1, '订单类型不能为空');
        }
        if (!in_array($data['pay_type'], ['wx', 'alipay'])) {
            return toJson(1, '支付类型不能为空');
        }
        $userAgent = $_SERVER['HTTP_USER_AGENT'];
        if (request()->isMobile() && $data['pay_type'] == 'wx' ){
            return toJson(1, '手机端暂不支持微信支付');
        }
        $order = (new PayOrderService())->getOrderModel($data['order_no'],$data['order_type']);
        if (empty($order)){
            return toJson(1, '订单不存在');
        }
        $key = $this->getArrKey[$order['version']];
        $product = $this->conf[$key] ?? '';
        if (empty($product)) {
            return toJson(1, '产品不存在');
        }
        try {
            if ($data['pay_type'] == 'alipay') {
                return (new AliPay())->webPay(['business_order_no' => $order['order_no'],'total_amount' => bcadd($product, 0, 2), 'subject' =>$order['version']. 'mbti测评报告'],request()->isMobile()  ? 'h5':'web');
            }
            $wx = (new wxPay())->createOrder(['business_order_no' => $order['order_no'],'total_fee' => bcadd($product, 0, 2), 'body' =>$order['version']. 'mbti测评报告']);
            return toJson(0, 'ok', $wx);
        } catch (\Exception $e) {
            return toJson(-1, $e->getMessage());
        }
    }
}